package com.crazy.web.controller;

import com.crazy.rest.RestResult;
import com.crazy.web.config.cos.CosConfig;
import com.crazy.web.config.cos.CosUtil;
import io.swagger.annotations.ApiResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author zhaochaofeng
 * @version 1.0
 * @date 2020/12/4 11:42
 */
@Log4j2
@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {

    @Autowired
    private CosConfig cosConfig;

    @ResponseBody
    @RequestMapping("/image")
    public RestResult image(@RequestParam("editormd-image-file") MultipartFile file) {
        ByteArrayInputStream bis = null;
        try{
            CosUtil cosUtil = new CosUtil(cosConfig.getAppId(), cosConfig.getSecretId(), cosConfig.getSecretKey(),
                    cosConfig.getRegion(), cosConfig.getBucketName());
            cosUtil.setup();
            byte [] byteArr=file.getBytes();
            bis = new ByteArrayInputStream(byteArr);
            String url = cosUtil.uploadImg(bis, file.getSize());
            cosUtil.shutdown();
            return RestResult.createSuccessResult("上传成功", url);
        }catch(Exception ex){
            return RestResult.createFailedResult("上传失败");
        }finally {
            if(bis!=null){
                try{
                    bis.close();
                }catch(IOException ex){
                    log.error(ex.getMessage());
                }
            }
        }
    }

}
